﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Bussiness;
using System.Data.Sql;
using System.Data;

namespace WebApplication.Admin
{
    public partial class ChiTietHoaDonXuatAdd : System.Web.UI.Page
    {
    
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadHienthi();
                LoadMathang();
                LoadKhachHang();
                LoadNhomhang();
                LoadNhanvien();
                DataTable datas = new DataTable();
                datas = (DataTable)Session["datakh"];
                
            }

        }
        public void LoadHienthi()
        {
            string strid = "" + Request["MAHDX"];
            IUnitOfWork iunitfwork = new EFUnitOfWork();
            CHITIETHOADONXUATRepository repository = new CHITIETHOADONXUATRepository(new EFRepository<CHITIETHOADONXUAT>(), iunitfwork);
            CHITIETHOADONXUAT objChitiethdx = null;
            if (!string.IsNullOrEmpty(strid))
            {
                objChitiethdx = repository.GetById(strid);
                txtmahdx.Value = objChitiethdx.MAHDX;
                txtsoluong.Value = objChitiethdx.SOLUONGXUAT.ToString();
                txtdongia.Value = objChitiethdx.GIATIEN.ToString();
                comboboxs.SelectedValue = objChitiethdx.HOADONXUAT.MAKH;
                Dlmathang.SelectedValue = objChitiethdx.MAMH;
                dlnhanvien.SelectedValue = objChitiethdx.HOADONXUAT.MANV;
                if (objChitiethdx.TINHTRANG == true)
                {
                    rdtt.Checked = true;
                }
                else
                {
                    rdchuatt.Checked = true;
                }
                LoadNhomhangtheomathang();
            }
        }
        /// <summary>
        /// Load Nhóm hàng theo mặt hàng
        /// </summary>
        /// <param name="mamh"></param>
        public void LoadNhomhangtheomathang()
        {
            IUnitOfWork iunitofwork = new EFUnitOfWork();
            string strid = "" + Request["MAHDX"];
            CHITIETHOADONXUATRepository repository = new CHITIETHOADONXUATRepository(new EFRepository<CHITIETHOADONXUAT>(), iunitofwork);
            NHOMHANGRepository repositoryNhomhang = new NHOMHANGRepository(new EFRepository<NHOMHANG>(), iunitofwork);
            MATHANGRepository repositorymathang = new MATHANGRepository(new EFRepository<MATHANG>(), iunitofwork);
            MATHANG objmathang = null;
            NHOMHANG objnhomhang = null;
            CHITIETHOADONXUAT objHoaDonN = null;
            if (!string.IsNullOrEmpty(strid))
            {
                string mamh="";
                objHoaDonN = repository.GetById(strid);
                if (objHoaDonN != null)
                {
                    mamh = objHoaDonN.MAMH;
                    objmathang = repositorymathang.All().Where(p => p.MAMH == mamh).FirstOrDefault();
                    objnhomhang = repositoryNhomhang.All().Where(p => p.MANH == objmathang.MANH).FirstOrDefault();
                    Dlnhomhang.SelectedValue = objnhomhang.MANH;
                    //LoadKhachHangTheoIDnhomhang(objnhomhang.MANH);
                    //LoadKhachHangTheoIDnhomhang(objnhomhang.MANH);
                }
               

            }
        }
        /// <summary>
        /// 'Load nhóm hàng
        /// </summary>
        public void LoadNhomhang()
        {
            IUnitOfWork iunitwork = new EFUnitOfWork();
            NHOMHANGRepository repository = new NHOMHANGRepository(new EFRepository<NHOMHANG>(), iunitwork);
            IQueryable<NHOMHANG> objnhomhang = repository.All();
            Dlnhomhang.DataSource = objnhomhang;
            Dlnhomhang.DataValueField = "MANH";
            Dlnhomhang.DataTextField = "TENNHOMHANG";
            Dlnhomhang.DataBind();
            Dlnhomhang.Items.Insert(0, new ListItem { Text="---Chọn nhóm hàng---",Value="0"});
        }
        /// <summary>
        /// Load Khách hàng
        /// </summary>
        public void LoadKhachHang()
        {
            IUnitOfWork iunitfwork = new EFUnitOfWork();
            KHACHHANGRepository repository = new KHACHHANGRepository(new EFRepository<KHACHHANG>(), iunitfwork);
            IQueryable<KHACHHANG> objkhachhang = repository.All();
            comboboxs.DataSource = objkhachhang;
            comboboxs.DataValueField = "MAKH";
            comboboxs.DataTextField = "TENKH";
            comboboxs.DataBind();
            comboboxs.Items.Insert(0, new ListItem { Text = "---Chọn khách hàng---", Value = "0" });

        }
        /// <summary>
        /// Load mặt hàng
        /// </summary>
        public void LoadMathang()
        {
            IUnitOfWork initwork = new EFUnitOfWork();
            MATHANGRepository repository = new MATHANGRepository(new EFRepository<MATHANG>(), initwork);
            IQueryable<MATHANG> objMathang = repository.All();
            Dlmathang.DataSource = objMathang;
            Dlmathang.DataValueField = "MAMH";
            Dlmathang.DataTextField = "TENMH";
            Dlmathang.DataBind();
            Dlmathang.Items.Insert(0, new ListItem { Text = "---Chọn mặt hàng---", Value = "0" });
        }
        /// <summary>
        /// Load Nhân viên
        /// </summary>
        public void LoadNhanvien()
        {
            IUnitOfWork iunitfwork = new EFUnitOfWork();
            NHANVIENRepository repository = new NHANVIENRepository(new EFRepository<NHANVIEN>(), iunitfwork);
            IQueryable<NHANVIEN> objnhanvien = repository.All();
            dlnhanvien.DataSource = objnhanvien;
            dlnhanvien.DataValueField = "MANV";
            dlnhanvien.DataTextField = "TENNV";
            dlnhanvien.DataBind();
            dlnhanvien.Items.Insert(0, new ListItem { Text = "---Chọn nhân viên---", Value = "0" });
        }
        public void capnhap()
        {
            
            bool iscapnhap = true;
            string strid = "" + Request["MAHDX"];
            IUnitOfWork iunitfwork = new EFUnitOfWork();
            CHITIETHOADONXUATRepository repository = new CHITIETHOADONXUATRepository(new EFRepository<CHITIETHOADONXUAT>(), iunitfwork);
            HOADONXUATRepository repositoryHDX = new HOADONXUATRepository(new EFRepository<HOADONXUAT>(), iunitfwork);
            TON_KHORepository repositoryTonkho = new TON_KHORepository(new EFRepository<TON_KHO>(), iunitfwork);
            DateTime dt = DateTime.Now;
            DateTime dts = Commomcs.convertDate(dt.ToString("dd/MM/yyyy"));
            TON_KHO objTonkho = null;
            bool istonkho = true;
            CHITIETHOADONXUAT objChitiethdx = null;
            HOADONXUAT objHDX = null;
            List<string> LstMahdx = new List<string>();
            IQueryable<CHITIETHOADONXUAT> LstchitietHdx = repository.All();
            string mahdx="";
            if (LstchitietHdx != null)
            {
                foreach (CHITIETHOADONXUAT hdx in LstchitietHdx)
                {
                    if (txtmahdx.Value == hdx.MAHDX)
                    {
                         mahdx = hdx.MAHDX;
                        LstMahdx.Add(mahdx);
                    }
                }
                if (LstMahdx.Count > 0)
                {
                    iscapnhap = false;
                }
            }
            if (!string.IsNullOrEmpty(strid))
            {
                iscapnhap = false;
                objChitiethdx = repository.GetById(strid);
                objHDX = repositoryHDX.GetById(strid);

            }
            if (string.IsNullOrEmpty(strid) && LstMahdx.Count > 0)
            {
                iscapnhap = false;
                objChitiethdx = repository.GetById(mahdx);
                objHDX = repositoryHDX.GetById(mahdx);
            }
            else if (string.IsNullOrEmpty(strid) && LstMahdx.Count <= 0)
            {
                iscapnhap = true;
                objChitiethdx = new CHITIETHOADONXUAT();
                objHDX = new HOADONXUAT();
            }
           
            if (string.IsNullOrEmpty(txtmahdx.Value) || comboboxs.SelectedValue.Equals("0") || Dlmathang.SelectedValue.Equals("0") || dlnhanvien.SelectedValue.Equals("0")|| string.IsNullOrEmpty(txtdongia.Value))
            {
                RegisterClientScriptBlock("Thông báo", "<script> alert ('Vui lòng nhập đầy đủ')</script>");
                return;
            }
            if (!string.IsNullOrEmpty(txtpt.Value))
            {
                if (int.Parse(txtpt.Value) <= 0)
                {
                    RegisterClientScriptBlock("Thông báo", "<script> alert ('Dữ liệu % ko đúng')</script>");
                    return;
                }
            }
          
            
            objHDX.MAHDX = txtmahdx.Value;
            objHDX.MANV = dlnhanvien.SelectedValue;
            objHDX.MAKH = comboboxs.SelectedValue;
            objHDX.NGAYXUAT = dts;
            objHDX.TIENPHAITRA = int.Parse(txtsoluong.Value) * int.Parse(txtdongia.Value);
            objChitiethdx.MAHDX = txtmahdx.Value;
            objChitiethdx.MAMH = Dlmathang.SelectedValue;
            objChitiethdx.SOLUONGXUAT = int.Parse(txtsoluong.Value);
            objChitiethdx.GIATIEN = int.Parse(txtdongia.Value);
            if (string.IsNullOrEmpty(txtsoluongvove.Value))
            {
                objChitiethdx.SOLUONGVOCUOC = 0;
                objChitiethdx.SOLUONGVOVE = 0;
            }
            int tiencuoc = 0;
            if (rdtt.Checked)
            {
                objChitiethdx.TINHTRANG = true;
            }
            else
            {
                objChitiethdx.TINHTRANG = false;
            }
            if (!string.IsNullOrEmpty(txtsoluongvove.Value))
            {
                objChitiethdx.SOLUONGVOVE = int.Parse(txtsoluongvove.Value);
                if (int.Parse(txtsoluong.Value) > int.Parse(txtsoluongvove.Value))
                {
                    objChitiethdx.SOLUONGVOCUOC = int.Parse(txtsoluong.Value) - int.Parse(txtsoluongvove.Value);
                    tiencuoc = 50000 * (int.Parse(txtsoluong.Value) - int.Parse(txtsoluongvove.Value));
                    objHDX.TIENPHAITRA = (int.Parse(txtsoluong.Value) * int.Parse(txtdongia.Value)) + tiencuoc;
                }
                if (int.Parse(txtsoluong.Value) < int.Parse(txtsoluongvove.Value))
                {
                    objChitiethdx.SOLUONGVOCUOC = int.Parse(txtsoluongvove.Value) - int.Parse(txtsoluong.Value);
                    tiencuoc = 50000 * (int.Parse(txtsoluongvove.Value) - int.Parse(txtsoluong.Value));
                    objHDX.TIENPHAITRA = (int.Parse(txtsoluong.Value) * int.Parse(txtdongia.Value)) - tiencuoc;
                }
                if (int.Parse(txtsoluong.Value) == int.Parse(txtsoluongvove.Value))
                {
                    objChitiethdx.SOLUONGVOCUOC = 0;
                    objHDX.TIENPHAITRA = (int.Parse(txtsoluong.Value) * int.Parse(txtdongia.Value));

                }
            }
            if (!string.IsNullOrEmpty(txtpt.Value))
            {
                objChitiethdx.GIAM_PT = int.Parse(txtpt.Value);
                objHDX.TIENPHAITRA = (((int.Parse(txtdongia.Value)- (int.Parse(txtpt.Value) * int.Parse(txtdongia.Value)))) / 100) * int.Parse(txtsoluong.Value);
                if (!string.IsNullOrEmpty(txtsoluongvove.Value))
                {
                    if (int.Parse(txtsoluong.Value) > int.Parse(txtsoluongvove.Value) && tiencuoc > 0)
                    {
                        objHDX.TIENPHAITRA = ((((int.Parse(txtdongia.Value)- (int.Parse(txtpt.Value) * int.Parse(txtdongia.Value)))) / 100) * int.Parse(txtsoluong.Value)) + tiencuoc;
                    }
                    if (int.Parse(txtsoluong.Value) < int.Parse(txtsoluongvove.Value) && tiencuoc > 0)
                    {
                        objHDX.TIENPHAITRA = ((((int.Parse(txtdongia.Value) - (int.Parse(txtpt.Value) * int.Parse(txtdongia.Value)))) / 100) * int.Parse(txtsoluong.Value)) - tiencuoc;
                    }
                }
                
            }
            if (rdtt.Checked)
            {
                objHDX.TINHTRANG = true;
                objChitiethdx.TINHTRANG = true;
            }
            else
            {
                objHDX.TINHTRANG = false;
                objChitiethdx.TINHTRANG = false;
            }
            try
            {
                if (iscapnhap)
                {
                    repositoryHDX.Add(objHDX);

                }
                repositoryHDX.Save();
                if (iscapnhap)
                {
                    repository.Add(objChitiethdx);
                }
                repository.Save();
            }
            catch (Exception ex)
            {
                RegisterClientScriptBlock("Thông báo", "<script> alert('Lỗi rồi')</script>");
            }
            //TON_KHO LstTonkho = repositoryTonkho.All().Where(p => p.NGAYTHANG == dts && p.MAMH == Dlmathang.SelectedValue).FirstOrDefault();
            //DateTime dthomtruoc = new DateTime();
            //TON_KHO objtonkhohomtruoc = null;
            //if (LstTonkho == null)
            //{
            //    string mamh = Dlmathang.SelectedValue;
            //    istonkho = true;
            //    dthomtruoc = Commomcs.DuyenNgayThang(mamh);
            //    objtonkhohomtruoc = repositoryTonkho.All().Where(p => p.NGAYTHANG == dthomtruoc && p.MAMH == Dlmathang.SelectedValue).FirstOrDefault();
            //    objTonkho = new TON_KHO();
            //}
            //if (LstTonkho != null)
            //{
            //    istonkho = false;
            //    objTonkho = repositoryTonkho.All().Where(p => p.NGAYTHANG == dts && p.MAMH == Dlmathang.SelectedValue).FirstOrDefault();
            //    if (!string.IsNullOrEmpty(LstTonkho.SOLUONGTON.ToString()))
            //    {
            //        hfton.Value = LstTonkho.SOLUONGTON.ToString();
            //    }
            //    if (!string.IsNullOrEmpty(LstTonkho.SOLUONGXUAT.ToString()))
            //    {
            //        hfxuat.Value = LstTonkho.SOLUONGXUAT.ToString();
            //    }
            //    else
            //    {
            //        hfxuat.Value = "0";
            //    }
            //}
            //objTonkho.NGAYTHANG = dts;
            //objTonkho.MAMH = Dlmathang.SelectedValue;
            //if (objtonkhohomtruoc != null)
            //{
            //    objTonkho.SOLUONGDAU = objtonkhohomtruoc.SOLUONGTON;
            //    objTonkho.SOLUONGTON = objTonkho.SOLUONGDAU - int.Parse(txtsoluong.Value);
            //    objTonkho.SOLUONGXUAT = int.Parse(txtsoluong.Value);
            //}
            //int sl;
            //if (objtonkhohomtruoc == null)
            //{
            //    objTonkho.SOLUONGTON = int.Parse(hfton.Value) - int.Parse(txtsoluong.Value);
            //    sl = (int)(int.Parse(txtsoluong.Value) + int.Parse(hfxuat.Value));
            //    objTonkho.SOLUONGXUAT = sl;
            //}
            //try
            //{
            //    if (istonkho)
            //    {
            //        repositoryTonkho.Add(objTonkho);
            //    }
            //    repositoryTonkho.Save();
            //    mhkh();
            //}
            //catch (Exception ex)
            //{
            //    RegisterClientScriptBlock("Thông báo", "<script> alert ('Lỗi rồi kiểm tra lại')</script>");
            //}
            TonKho();
            mhkh();
        }

     public void mhkh()
        {
            DataTable datakh1 = new DataTable();
            DataTable data = new DataTable();
            data.Columns.Add("mahd", typeof(string));
            data.Columns.Add("mathang", typeof(string));
            data.Columns.Add("soluong", typeof(int));
            data.Columns.Add("dongia", typeof(int));
            data.Columns.Add("tongtien", typeof(int));
            data.Columns.Add("khachhang", typeof(string));
            data.Columns.Add("nhanvien", typeof(string));
            data.Columns.Add("diachi", typeof(string));
            data.Columns.Add("sdt", typeof(string));
            data.Columns.Add("donvitinh", typeof(string));
            data.Columns.Add("tinhtrang", typeof(string));

            IUnitOfWork iunitfwork = new EFUnitOfWork();
            CHITIETHOADONXUATRepository repository = new CHITIETHOADONXUATRepository(new EFRepository<CHITIETHOADONXUAT>(), iunitfwork);
            CHITIETHOADONXUAT objchitiethdx = null;
            if (Session["datakh"] == null)
            {
                objchitiethdx = repository.All().Where(p => p.MAHDX == txtmahdx.Value).FirstOrDefault();
                DataRow rows = data.NewRow();
                rows["mahd"] = txtmahdx.Value;
                rows["mathang"] = Dlmathang.SelectedItem;
                rows["soluong"] = txtsoluong.Value;
                rows["dongia"] = txtdongia.Value;
                rows["tongtien"] = int.Parse(txtsoluong.Value) * int.Parse(txtdongia.Value);
                rows["khachhang"] = comboboxs.SelectedItem;
                rows["nhanvien"] = dlnhanvien.SelectedItem;
                if(objchitiethdx !=null)
                {
                    rows["diachi"] = objchitiethdx.HOADONXUAT.KHACHHANG.DIACHI;
                    rows["sdt"] = objchitiethdx.HOADONXUAT.KHACHHANG.SDT;
                    if (!string.IsNullOrEmpty(objchitiethdx.MATHANG.DONVITINH.DONVITINH1))
                    {
                        rows["donvitinh"] = objchitiethdx.MATHANG.DONVITINH.DONVITINH1;
                    }
                    if (rdtt.Checked)
                    {
                        rows["tinhtrang"] = "Đã thanh toán";
                    }
                    else
                    {
                        rows["tinhtrang"] = "Chưa thanh toán";
                    }
                }
                data.Rows.Add(rows);
            }
           
            else
            {
                datakh1 = (DataTable)Session["datakh"];
                if ( comboboxs.SelectedItem.ToString().Trim().Equals(datakh1.Rows[0]["khachhang"].ToString().Trim()))
                {
                    data = (DataTable)Session["datakh"];
                    DataRow rows = data.NewRow();
                    rows["mahd"] = txtmahdx.Value;
                    rows["mathang"] = Dlmathang.SelectedItem;
                    rows["soluong"] = txtsoluong.Value;
                    rows["dongia"] = txtdongia.Value;
                    rows["tongtien"] = int.Parse(txtsoluong.Value) * int.Parse(txtdongia.Value);
                    rows["khachhang"] = comboboxs.SelectedItem;
                    rows["nhanvien"] = dlnhanvien.SelectedItem;
                    if (objchitiethdx != null)
                    {
                        rows["diachi"] = objchitiethdx.HOADONXUAT.KHACHHANG.DIACHI;
                        rows["sdt"] = objchitiethdx.HOADONXUAT.KHACHHANG.SDT;
                        if (!string.IsNullOrEmpty(objchitiethdx.MATHANG.DONVITINH.DONVITINH1))
                        {
                            rows["donvitinh"] = objchitiethdx.MATHANG.DONVITINH.DONVITINH1;
                        }
                        if (rdtt.Checked)
                        {
                            rows["tinhtrang"] = "Đã thanh toán";
                        }
                        else
                        {
                            rows["tinhtrang"] = "Chưa thanh toán";
                        }
                    }
                    data.Rows.Add(rows);
                }
                else
                {
                    data = new DataTable();
                    data.Columns.Add("mahd", typeof(string));
                    data.Columns.Add("mathang", typeof(string));
                    data.Columns.Add("soluong", typeof(int));
                    data.Columns.Add("dongia", typeof(int));
                    data.Columns.Add("tongtien", typeof(int));
                    data.Columns.Add("khachhang", typeof(string));
                    data.Columns.Add("nhanvien", typeof(string));
                    DataRow rows = data.NewRow();
                    rows["mahd"] = txtmahdx.Value;
                    rows["mathang"] = Dlmathang.SelectedItem;
                    rows["soluong"] = txtsoluong.Value;
                    rows["dongia"] = txtdongia.Value;
                    rows["tongtien"] = int.Parse(txtsoluong.Value) * int.Parse(txtdongia.Value);
                    rows["khachhang"] = comboboxs.SelectedItem;
                    rows["nhanvien"] = dlnhanvien.SelectedItem;
                    data.Columns.Add("tinhtrang", typeof(string));
                    if (objchitiethdx != null)
                    {
                        rows["diachi"] = objchitiethdx.HOADONXUAT.KHACHHANG.DIACHI;
                        rows["sdt"] = objchitiethdx.HOADONXUAT.KHACHHANG.SDT;
                        if (!string.IsNullOrEmpty(objchitiethdx.MATHANG.DONVITINH.DONVITINH1))
                        {
                            rows["donvitinh"] = objchitiethdx.MATHANG.DONVITINH.DONVITINH1;
                        }
                        if (rdtt.Checked)
                        {
                            rows["tinhtrang"] = "Đã thanh toán";
                        }
                        else
                        {
                            rows["tinhtrang"] = "Chưa thanh toán";
                        }
                    }
                    data.Rows.Add(rows);
                }
            }
            //DataTable datas = new DataTable();
            //datas = (DataTable)Session["datakh"];
            Session["datakh"] = data;
            if (Session["datakh"] != null)
            {
                Grdanhsach.DataSource = Session["datakh"];
                Grdanhsach.DataBind();
            }
        }
        protected void lbtncapnhap_Click(object sender, EventArgs e)
        {
            /// Kiểm tra còn hàng hay không
            bool istonkho = true;
            IUnitOfWork iunitfwork = new EFUnitOfWork();
            TON_KHORepository repositoryTonkho = new TON_KHORepository(new EFRepository<TON_KHO>(), iunitfwork);
            DateTime dt = Commomcs.convertDate(DateTime.Now.ToString("dd/MM/yyyy"));
            DateTime dts = Commomcs.convertDate(dt.ToString("dd/MM/yyyy"));
            TON_KHO objTonkho = null;
            TON_KHO LstTonkho = repositoryTonkho.All().Where(p =>p.NGAYTHANG==dts && p.MAMH == Dlmathang.SelectedValue).FirstOrDefault();
            DateTime dthomtruoc = new DateTime();
            TON_KHO objtonkhohomtruoc = null;
            if (LstTonkho == null)
            {
                string mamh = Dlmathang.SelectedValue;
                istonkho = true;
                dthomtruoc = Commomcs.DuyenNgayThang(mamh);
                objtonkhohomtruoc = repositoryTonkho.All().Where(p => p.NGAYTHANG == dthomtruoc && p.MAMH == Dlmathang.SelectedValue).FirstOrDefault();
                if (objtonkhohomtruoc != null)
                {
                    if (objtonkhohomtruoc.SOLUONGTON <= 0)
                    {
                        RegisterClientScriptBlock("Thông báo", "<script> alert('Hết hàng')</script>");
                        return;
                    }
                }
                if (objtonkhohomtruoc == null)
                {
                    RegisterClientScriptBlock("Thông báo", "<script> alert('Hết hàng')</script>");
                    return;
                }
                objTonkho = new TON_KHO();
            }
            if (LstTonkho != null)
            {
                istonkho = false;
                objTonkho = repositoryTonkho.All().Where(p => p.NGAYTHANG == dts && p.MAMH == Dlmathang.SelectedValue).FirstOrDefault();
                if (objTonkho.SOLUONGTON <= 0)
                {
                    RegisterClientScriptBlock("Thông báo", "<script> alert('Hết hàng')</script>");
                    return;
                }
            }
            ///
            ///Cap nhập
            capnhap();
            tonkhovo();
            int tiencuoc = 0;
            int tongtien = int.Parse(txtsoluong.Value) * int.Parse(txtdongia.Value);
            if (rdchuatt.Checked)
            {
                string mkh = comboboxs.SelectedValue;
                if (!string.IsNullOrEmpty(txtsoluongvove.Value))
                {

                    if (int.Parse(txtsoluong.Value) > int.Parse(txtsoluongvove.Value))
                    {

                        tiencuoc = 50000 * (int.Parse(txtsoluong.Value) - int.Parse(txtsoluongvove.Value));
                        tongtien = (int.Parse(txtsoluong.Value) * int.Parse(txtdongia.Value)) + tiencuoc;
                    }
                    if (int.Parse(txtsoluong.Value) < int.Parse(txtsoluongvove.Value))
                    {

                        tiencuoc = 50000 * (int.Parse(txtsoluongvove.Value) - int.Parse(txtsoluong.Value));
                        tongtien = (int.Parse(txtsoluong.Value) * int.Parse(txtdongia.Value)) - tiencuoc;
                    }
                    if (int.Parse(txtsoluong.Value) == int.Parse(txtsoluongvove.Value))
                    {

                        tongtien = (int.Parse(txtsoluong.Value) * int.Parse(txtdongia.Value));

                    }
                   
                }
                RegisterClientScriptBlock("Thông báo", "<script> alert('Vui lòng nhập công nợ khách hàng')</script>");
            }
            Session["Tongtienkh"] = tongtien.ToString();
            //Response.Redirect("CongnoKhAdd.aspx?MAKH=" + mkh);
        }
        public void Kiemtrahangtrongkho()
        {
            bool istonkho = true;
            IUnitOfWork iunitfwork = new EFUnitOfWork();
            TON_KHORepository repositoryTonkho = new TON_KHORepository(new EFRepository<TON_KHO>(), iunitfwork);
            DateTime dt = DateTime.Now;
            DateTime dts = Commomcs.convertDate(dt.ToString("dd/MM/yyyy"));
            TON_KHO objTonkho = null;
            TON_KHO LstTonkho = repositoryTonkho.All().Where(p => p.NGAYTHANG == dts && p.MAMH == Dlmathang.SelectedValue).FirstOrDefault();
            DateTime dthomtruoc = new DateTime();
            TON_KHO objtonkhohomtruoc = null;
            if (LstTonkho == null)
            {
                string mamh = Dlmathang.SelectedValue;
                istonkho = true;
                dthomtruoc = Commomcs.DuyenNgayThang(mamh);
                objtonkhohomtruoc = repositoryTonkho.All().Where(p => p.NGAYTHANG == dthomtruoc && p.MAMH == Dlmathang.SelectedValue).FirstOrDefault();
                if (objtonkhohomtruoc != null)
                {
                    if (objtonkhohomtruoc.SOLUONGTON <= 0)
                    {
                        RegisterClientScriptBlock("Thông báo", "<script> alert('Hết hàng')</script>");
                        return;
                    }
                }
                if (objtonkhohomtruoc == null)
                {
                    RegisterClientScriptBlock("Thông báo", "<script> alert('Hết hàng')</script>");
                    return;
                }
                objTonkho = new TON_KHO();
            }
            if (LstTonkho != null)
            {
                istonkho = false;
                objTonkho = repositoryTonkho.All().Where(p => p.NGAYTHANG == dts && p.MAMH == Dlmathang.SelectedValue).FirstOrDefault();
                if (objTonkho.SOLUONGTON <= 0)
                {
                    RegisterClientScriptBlock("Thông báo", "<script> alert('Hết hàng')</script>");
                    return;
                }
            }

        }
        public void tonkhovo()
        {
            string mamh = Dlmathang.SelectedValue;
            DateTime dt = Commomcs.convertDate(DateTime.Now.ToString("dd/MM/yyyy"));
            DateTime dtHtruoc = Commomcs.DuyenNgayThangtonvo(mamh);
            IUnitOfWork iunitfwork = new EFUnitOfWork();
            TONKHO_VORepository repositoryTonKhovo = new TONKHO_VORepository(new EFRepository<TONKHO_VO>(), iunitfwork);
            CHITIETHOADONXUATRepository repositoryChitietHDX = new CHITIETHOADONXUATRepository(new EFRepository<CHITIETHOADONXUAT>(), iunitfwork);
            HOADONXUATRepository repositoryHDX1 = new HOADONXUATRepository(new EFRepository<HOADONXUAT>(), iunitfwork);
            CHITIETHOADONNHAPRepository repositoryCtietHDN = new CHITIETHOADONNHAPRepository(new EFRepository<CHITIETHOADONNHAP>(), iunitfwork);
            XUATVORepository repositoryXuatVo = new XUATVORepository(new EFRepository<XUATVO>(), iunitfwork);
            IQueryable<XUATVO> LstXuatvo = repositoryXuatVo.All().Where(p => p.MAMH == "Dl19l" && p.NGAYTHANG == dt);
            IQueryable<CHITIETHOADONNHAP> LstHDn = repositoryCtietHDN.All().Where(p => p.MAMH == "Dl19l" && p.HOADONNHAP.NGAYNHAP == dt);
            IQueryable<CHITIETHOADONXUAT> LstHDx = repositoryChitietHDX.All().Where(p => p.MAMH == "Dl19l" && p.HOADONXUAT.NGAYXUAT == dt);
            int tongslvoxuat = 0;
            int Tongslxuat = 0;
            int Tongslnhap = 0;
            bool iscapnhap = true;
            if (LstXuatvo != null)
            {
                foreach (XUATVO Xv in LstXuatvo)
                {
                    tongslvoxuat += (int)Xv.SOLUONGXUAT;
                }
            }
            if (LstHDn != null)
            {
                foreach (CHITIETHOADONNHAP hdn in LstHDn)
                {
                    Tongslnhap += (int)hdn.SOLUONGNHAP;
                }
            }
            if (LstHDx != null)
            {
                foreach (CHITIETHOADONXUAT hdx in LstHDx)
                {
                    if (!string.IsNullOrEmpty(hdx.SOLUONGVOVE.ToString()))
                    {
                        Tongslxuat += (int)hdx.SOLUONGVOVE;
                    }

                }
            }
            TONKHO_VO objtonkho = null;
            TONKHO_VO objtonkhoht = null;
            if (Dlmathang.SelectedValue.Equals("Dl19l"))
            {
                objtonkho = repositoryTonKhovo.All().Where(p => p.NGAYTHANG == dt && p.MAMH == mamh).FirstOrDefault();
                if (objtonkho != null)
                {
                    iscapnhap = false;
                    int sldau = (int)objtonkho.SOLUONGVODAU;
                    int slnhap = (int)objtonkho.SOLUONGVONHAP;
                    int slam = (int)objtonkho.AMVO;
                    int slxuat = (int)objtonkho.SOLUONGVOXUAT;
                    objtonkho.SOLUONGVODAU = sldau;
                    objtonkho.SOLUONGVONHAP = Tongslxuat;
                    objtonkho.SOLUONGVOXUAT = tongslvoxuat;
                    objtonkho.SOLUONGVOTONCUOI = Tongslxuat + sldau - tongslvoxuat;
                }
                if (objtonkho == null)
                {
                    iscapnhap = true;
                    objtonkho = new TONKHO_VO();
                    objtonkho.MAMH = Dlmathang.SelectedValue;
                    objtonkho.NGAYTHANG = dt;
                    objtonkhoht = repositoryTonKhovo.All().Where(p => p.NGAYTHANG == dtHtruoc && p.MAMH == "Dl19l").FirstOrDefault();
                    if (objtonkhoht == null)
                    {
                        objtonkho.SOLUONGVODAU = 0;
                        objtonkho.SOLUONGVONHAP = Tongslxuat;
                        objtonkho.SOLUONGVOXUAT = tongslvoxuat;
                        objtonkho.SOLUONGVOTONCUOI = Tongslxuat;
                        objtonkho.AMVO = 0;
                    }
                    if (objtonkhoht != null)
                    {
                        objtonkho.SOLUONGVODAU = objtonkhoht.SOLUONGVOTONCUOI;
                        objtonkho.SOLUONGVONHAP = Tongslxuat;
                        objtonkho.SOLUONGVOXUAT = tongslvoxuat;
                        objtonkho.SOLUONGVOTONCUOI = Tongslxuat + objtonkhoht.SOLUONGVOTONCUOI - tongslvoxuat;
                        objtonkho.AMVO = 0;
                    }
                }
                try
                {
                    if (iscapnhap)
                    {
                        repositoryTonKhovo.Add(objtonkho);
                    }
                    repositoryTonKhovo.Save();
                }
                catch (Exception ex)
                {

                }
            }
        }
        

        //protected void lbxuathd_Click(object sender, EventArgs e)
        //{
        //    Response.Redirect("HoaDonXuat.aspx");
        //}

        protected void lbtnthemmoi_Click(object sender, EventArgs e)
        {
            txtmahdx.Value = "";
            txtdongia.Value = "";
            txtpt.Value = "";
            txtsoluong.Value = "";
            txtsoluongvove.Value = "";
            dlnhanvien.SelectedValue = "0";
            Dlmathang.SelectedValue = "0";
            Response.Redirect("ChiTietHoaDonXuatAdd.aspx");
        }
        /// <summary>
        /// Lấy mặt hàng theo nhóm hàng
        /// </summary>
        /// <param name="manh"></param>
        public void LoadMatHangTheoIdnhomhang(string manh)
        {
            IUnitOfWork iunitfwork = new EFUnitOfWork();
            MATHANGRepository repository = new MATHANGRepository(new EFRepository<MATHANG>(), iunitfwork);
            IQueryable<MATHANG> objmathang = repository.All().Where(p => p.MANH == manh);
            Dlmathang.DataSource = objmathang;
            Dlmathang.DataValueField = "MAMH";
            Dlmathang.DataTextField = "TENMH";
            Dlmathang.DataBind();
            Dlmathang.Items.Insert(0, new ListItem { Text="--Chọn mặt hàng---",Value="0" });
        }
        /// <summary>
        /// Lấy khách hàng theo nhóm hàng
        /// </summary>
        /// <param name="manh"></param>
        public void LoadKhachHangTheoIDnhomhang(string manh)
        {
            IUnitOfWork iunitfwork = new EFUnitOfWork();
            KHACHHANGRepository repository = new KHACHHANGRepository(new EFRepository<KHACHHANG>(), iunitfwork);
            IQueryable<KHACHHANG> objkhachhang = repository.All().Where(p => p.MANH == manh);
            comboboxs.DataSource = objkhachhang;
            comboboxs.DataValueField = "MAKH";
            comboboxs.DataTextField = "TENKH";
            comboboxs.DataBind();
            comboboxs.Items.Insert(0, new ListItem {Text="---Chọn khách hàng---",Value="0" });

        }
        protected void Dlnhomhang_SelectedIndexChanged(object sender, EventArgs e)
        {
            string manh = Dlnhomhang.SelectedValue;
            LoadMatHangTheoIdnhomhang(manh);
            LoadKhachHangTheoIDnhomhang(manh);

        }
        public void TonKho()
        {
            string mamh=Dlmathang.SelectedValue;
            DateTime dt = Commomcs.convertDate(DateTime.Now.ToString("dd/MM/yyyy"));
            DateTime dtHtruoc = Commomcs.DuyenNgayThang(mamh);
            IUnitOfWork iunitfwork = new EFUnitOfWork();
            TON_KHORepository repositoryTonKho = new TON_KHORepository(new EFRepository<TON_KHO>(), iunitfwork);
            CHITIETHOADONXUATRepository repositoryChitietHDX = new CHITIETHOADONXUATRepository(new EFRepository<CHITIETHOADONXUAT>(), iunitfwork);
            HOADONNHAPRepository repositoryHdn = new HOADONNHAPRepository(new EFRepository<HOADONNHAP>(), iunitfwork);
            int Tongslxuat = 0;
            int Tongslnhap = 0;
            IQueryable<HOADONNHAP> LstHdn = repositoryHdn.All().Where(p => p.CHITIETHOADONNHAP.MAMH == mamh && p.NGAYNHAP == dt);
            IQueryable<CHITIETHOADONXUAT> LstHdx = repositoryChitietHDX.All().Where(p => p.HOADONXUAT.NGAYXUAT == dt && p.MAMH == mamh);
            if (LstHdn != null)
            {
                foreach (HOADONNHAP hdn in LstHdn)
                {
                    Tongslnhap +=(int) hdn.CHITIETHOADONNHAP.SOLUONGNHAP;
                }
            }
            if (LstHdx != null)
            {
                foreach (CHITIETHOADONXUAT hdx in LstHdx)
                {
                    Tongslxuat += (int)hdx.SOLUONGXUAT;
                }
            }
            TON_KHO TonkhoHientai=null;
            TON_KHO tonkho = null;
            TON_KHO TonkhoHt=null;
            bool iscapnhap = true;
                TonkhoHientai = repositoryTonKho.All().Where(p => p.MAMH == mamh && p.NGAYTHANG == dt).FirstOrDefault();
                if (TonkhoHientai != null)
                {
                    iscapnhap = false;
                    int sldau =(int) TonkhoHientai.SOLUONGDAU;
                    int slnhap = (int)TonkhoHientai.SOLUONGNHAP;
                    int slxuat = (int)TonkhoHientai.SOLUONGXUAT;
                    int slton = (int)TonkhoHientai.SOLUONGTON;
                    TonkhoHientai.NGAYTHANG = dt;
                    TonkhoHientai.MAMH = Dlmathang.SelectedValue;
                    TonkhoHientai.SOLUONGDAU = sldau;
                    TonkhoHientai.SOLUONGNHAP = Tongslnhap;
                    TonkhoHientai.SOLUONGXUAT = Tongslxuat;
                    TonkhoHientai.SOLUONGTON = (Tongslnhap + sldau) - Tongslxuat;
                   
                }
                if (TonkhoHientai == null)
                {
                    iscapnhap = true;
                    TonkhoHientai = new TON_KHO();
                    TonkhoHientai.NGAYTHANG = dt;
                    TonkhoHientai.MAMH = Dlmathang.SelectedValue;
                    TonkhoHientai.SOLUONGNHAP = Tongslnhap;
                    TonkhoHientai.SOLUONGXUAT = Tongslxuat;
                    TonkhoHt = repositoryTonKho.All().Where(p => p.NGAYTHANG == dtHtruoc && p.MAMH == mamh).FirstOrDefault();
                    if (TonkhoHt == null)
                    {
                        TonkhoHientai.SOLUONGDAU = 0;
                        TonkhoHientai.SOLUONGTON = Tongslnhap - Tongslxuat;
                    }
                    if (TonkhoHt != null)
                    {
                        TonkhoHientai.SOLUONGDAU = TonkhoHt.SOLUONGTON;
                        TonkhoHientai.SOLUONGTON = TonkhoHt.SOLUONGTON + Tongslnhap - Tongslxuat;
                    }
                   
                    
                }
                try
                {
                    if (iscapnhap)
                    {
                        repositoryTonKho.Add(TonkhoHientai);
                    }
                    repositoryTonKho.Save();
                }
                catch
                {
                    RegisterClientScriptBlock("Thông báo", "<script> alert('Vui lòng nhập lại')</script>");
                }
            }

        protected void comboboxs_SelectedIndexChanged(object sender, EventArgs e)
        {
            LayGiaTheoKhachHang();
        }
        public void LayGiaTheoKhachHang()
        {
            IUnitOfWork iunitfwork = new EFUnitOfWork();
            KHACHHANGRepository repository = new KHACHHANGRepository(new EFRepository<KHACHHANG>(), iunitfwork);
            KHACHHANG objkhachhang = null;
            if (!comboboxs.SelectedValue.Equals("0"))
            {
                objkhachhang = repository.All().Where(p => p.MAKH == comboboxs.SelectedValue).First();
                if (objkhachhang != null)
                {
                    txtgiakh.Value = objkhachhang.GIABAN.ToString();
                }
            }
        }

        protected void comboboxs_SelectedIndexChanged1(object sender, EventArgs e)
        {
            GiatheoKH();
        }
        public void GiatheoKH()
        {
            IUnitOfWork iunitfwork = new EFUnitOfWork();
            KHACHHANGRepository repository = new KHACHHANGRepository(new EFRepository<KHACHHANG>(), iunitfwork);
            KHACHHANG objkhachhang = null;
            if (!comboboxs.SelectedValue.Equals("0"))
            {
                string makh = comboboxs.SelectedValue;
                objkhachhang = repository.All().Where(p => p.MAKH == makh).FirstOrDefault();
                if (objkhachhang != null)
                {
                    txtgiakh.Value = objkhachhang.GIABAN.ToString();
                }
            }
        }

        protected void Unnamed3_Click(object sender, EventArgs e)
        {
        
            
        }
        
    }
}